﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HCSAnalyzer.Classes.Base_Classes.DataStructures;
using HCSAnalyzer.GUI.FormsForGraphsDisplay.Generic;
using HCSAnalyzer.Classes.General_Types;
using System.Windows.Forms;
using LibPlateAnalysis;
using HCSAnalyzer.Classes.Base_Classes.DataProcessing;
using HCSAnalyzer.Classes.Base_Classes.Viewers._1D;
using System.Windows.Forms.DataVisualization.Charting;
using HCSAnalyzer.Classes.Base_Classes.DataAnalysis;

namespace HCSAnalyzer.Classes.Base_Classes.Viewers
{
    class cViewerListWellsTreeView : cDataDisplay
    {
        //public cChart2DScatterPoint Chart = new cChart2DScatterPoint();
        List<cListWells> Input;
        TreeView TV;

        public cViewerListWellsTreeView()
        {
            this.Title = "List Wells Tree View";
        }

        public void SetInputData(List<cListWells> Input)
        {
            this.Input = Input;
        }

        public cFeedBackMessage Run()
        {
            try
            {
                if (this.Input == null)
                {
                    base.FeedBackMessage.IsSucceed = false;
                    base.FeedBackMessage.Message = "No Input Data !";
                    return base.FeedBackMessage;
                }

                this.CurrentPanel = new cExtendedControl();
                this.CurrentPanel.Title = this.Title;
                this.CurrentPanel.Anchor = (System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom
                                            | System.Windows.Forms.AnchorStyles.Left
                                            | System.Windows.Forms.AnchorStyles.Right);

                TV = new TreeView();
                //TV.CheckBoxes = true;
                //  TV.MouseClick += new MouseEventHandler(TV_MouseClick);
                TV.NodeMouseClick += new TreeNodeMouseClickEventHandler(TV_NodeMouseClick);
                // TV.MouseMove += new MouseEventHandler(TV_MouseMove);    

                foreach (var item in this.Input)
                {
                    TV.Nodes.Add(item.GetAssociatedTreeNode());
                }

                TV.Anchor = (System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom
                                            | System.Windows.Forms.AnchorStyles.Left
                                            | System.Windows.Forms.AnchorStyles.Right);


                CurrentPanel.Controls.Add(TV);

            }
            catch (Exception e)
            {
                cGlobalInfo.WindowHCSAnalyzer.richTextBoxConsole.AppendText("Component [" + this.Title + "] error:\n" + e.Message + "\n\n");
                base.FeedBackMessage.IsSucceed = false;
            }

            return base.FeedBackMessage;
        }

        //void TV_MouseMove(object sender, MouseEventArgs e)
        //{
        //    // Get the node at the current mouse pointer location.
        //    TreeNode theNode = this.TV.GetNodeAt(e.X, e.Y);

        //    ToolTip toolTip1 = new ToolTip();

        //    // Set a ToolTip only if the mouse pointer is actually paused on a node.
        //    if ((theNode != null))
        //    {
        //        // Verify that the tag property is not "null".
        //        if (theNode.Tag != null)
        //        {
        //            // Change the ToolTip only if the pointer moved to a new node.
        //            if (theNode.Tag.ToString() != toolTip1.GetToolTip(this.TV))
        //            {
        //                toolTip1.SetToolTip(this.TV, theNode.Tag.ToString());
        //            }
        //        }
        //        else
        //        {
        //            toolTip1.SetToolTip(this.TV, "");
        //        }
        //    }
        //    else     // Pointer is not over a node so clear the ToolTip.
        //    {
        //        toolTip1.SetToolTip(this.TV, "");
        //    }

        //}

        void TV_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Clicks != 1) return;

            if (e.Button != MouseButtons.Right) return;

            ContextMenuStrip NewMenu = new ContextMenuStrip();

            foreach (var item in GetBasicMenu())
            {
                NewMenu.Items.Add(item);
            }

            NewMenu.Items.Add(new ToolStripSeparator());
            if (e.Node.Tag == null) return;

            if (e.Node.Tag.GetType() == typeof(cWell))
            {
                foreach (var item in ((cWell)e.Node.Tag).GetExtendedContextMenu())
                    NewMenu.Items.Add(item);
            }
            else if (e.Node.Tag.GetType() == typeof(cListWells))
            {
                NewMenu.Items.Add(((cListWells)e.Node.Tag).GetExtendedContextMenu());
            }

            NewMenu.DropShadowEnabled = true;
            NewMenu.Show(Control.MousePosition);

        }



        public List<ToolStripMenuItem> GetBasicMenu()
        {
            List<ToolStripMenuItem> NewMenu = new List<ToolStripMenuItem>();

            ToolStripMenuItem ToolStripMenuItem_CollapseAll = new ToolStripMenuItem("Collapse All");
            ToolStripMenuItem_CollapseAll.Click += new EventHandler(ToolStripMenuItem_CollapseAll_Click);
            NewMenu.Add(ToolStripMenuItem_CollapseAll);

            ToolStripMenuItem ToolStripMenuItem_ExpandAll = new ToolStripMenuItem("Expand All");
            ToolStripMenuItem_ExpandAll.Click += new EventHandler(ToolStripMenuItem_ExpandAll_Click);
            NewMenu.Add(ToolStripMenuItem_ExpandAll);

            ToolStripMenuItem ToolStripMenuItem_DRCAnalysis = new ToolStripMenuItem("DRC Analysis (" + cWell.Parent.ListDescriptors.GetActiveDescriptor().GetName() + ")");
            ToolStripMenuItem_DRCAnalysis.Click += new EventHandler(ToolStripMenuItem_DRCAnalysis_Click);
            NewMenu.Add(ToolStripMenuItem_DRCAnalysis);

            return NewMenu;
        }

        void TV_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Clicks != 1) return;

            if (e.Button != MouseButtons.Right) return;

            ContextMenuStrip NewMenu = new ContextMenuStrip();

            foreach (var item in GetBasicMenu())
            {
                NewMenu.Items.Add(item);
            }



            //foreach (var item in base.GetContextMenu(e))
            //    NewMenu.Items.Add(item);
            //NewMenu.Items.Add(this.GetContextMenu());

            //#region Selection process
            //double MaxX = this.ChartAreas[0].CursorX.SelectionEnd;
            //double MinX = this.ChartAreas[0].CursorX.SelectionStart;

            //if (MaxX < MinX)
            //{
            //    MinX = this.ChartAreas[0].CursorX.SelectionEnd;
            //    MaxX = this.ChartAreas[0].CursorX.SelectionStart;
            //}

            //double MaxY = this.ChartAreas[0].CursorY.SelectionEnd;
            //double MinY = this.ChartAreas[0].CursorY.SelectionStart;

            //if (MaxY < MinY)
            //{
            //    MinY = this.ChartAreas[0].CursorY.SelectionEnd;
            //    MaxY = this.ChartAreas[0].CursorY.SelectionStart;
            //}

            ////cListWell ListWells = new cListWell();
            //List<DataPoint> LDP = new List<DataPoint>();

            //foreach (DataPoint item in this.Series[0].Points)
            //{
            //    if ((item.XValue >= MinX) && (item.XValue <= MaxX) && (item.YValues[0] >= MinY) && (item.YValues[0] <= MaxY))
            //    {
            //        if ((item.Tag != null) && (item.Tag.GetType() == typeof(cWell)))
            //        {
            //            // ListWells.Add((cWell)(item.Tag));
            //            LDP.Add(item);

            //            //((cWell)(item.Tag)).SetClass(5);
            //            //item.Color = ((cWell)(item.Tag)).GetClassColor();
            //        }
            //    }
            //}

            //if (LDP.Count > 0)
            //{
            //    ToolStripMenuItem SpecificContextMenu = new ToolStripMenuItem("List " + LDP.Count + " wells");
            //    ToolStripMenuItem ToolStripMenuItem_ChangeClass = new ToolStripMenuItem("Classes");
            //    //ToolStripMenuItem_CopyClassToClipBoard.Click += new System.EventHandler(this.ToolStripMenuItem_CopyClassToClipBoard);
            //    SpecificContextMenu.DropDownItems.Add(ToolStripMenuItem_ChangeClass);

            //    cWell TmpWell = (cWell)(LDP[0].Tag);

            //    for (int i = 0; i < cWell.Parent.GlobalInfo.ListWellClasses.Count; i++)
            //    {
            //        ToolStripMenuItem ToolStripMenuItem_NewClass = new ToolStripMenuItem(cWell.Parent.GlobalInfo.ListWellClasses[i].Name);
            //        ToolStripMenuItem_NewClass.Click += new System.EventHandler(this.ToolStripMenuItem_NewClass);
            //        ToolStripMenuItem_NewClass.Tag = LDP;
            //        ToolStripMenuItem_ChangeClass.DropDownItems.Add(ToolStripMenuItem_NewClass);
            //    }
            //    NewMenu.Items.Add(SpecificContextMenu);
            //}
            //#endregion

            NewMenu.DropShadowEnabled = true;
            NewMenu.Show(Control.MousePosition);
        }

        void ToolStripMenuItem_DRCAnalysis_Click(object sender, EventArgs e)
        {
            //TV.ExpandAll();
            List<cDescriptorType> ListSelectedDesc = new List<cDescriptorType>();// GlobalInfo.CurrentScreening.ListDescriptors.GetActiveDescriptors();        
            ListSelectedDesc.Add(cWell.Parent.ListDescriptors.GetActiveDescriptor());

            {
                //  GlobalInfo = (cGlobalInfo)this.Sender;
                if (GlobalInfo == null)
                    GlobalInfo = cWell.Parent.GlobalInfo;
                if (GlobalInfo == null) return;
                //int DescriptorIdx = GlobalInfo.CurrentScreen.ListDescriptors.GetDescriptorIndex(GlobalInfo.CurrentScreen.ListDescriptors.GetActiveDescriptor());

                //cDesignerTab DT = new cDesignerTab();  
                cDesignerMultiChoices DT = new cDesignerMultiChoices();
                // DT.IsMultiline = true;

                cExtendedTable TableForGeneralResuts = new cExtendedTable();
                TableForGeneralResuts.Add(new cExtendedList("p-Value"));
                TableForGeneralResuts.Add(new cExtendedList("EC50"));
                TableForGeneralResuts.Add(new cExtendedList("Slope"));
                TableForGeneralResuts.Add(new cExtendedList("Bottom"));
                TableForGeneralResuts.Add(new cExtendedList("Top"));
                TableForGeneralResuts.Add(new cExtendedList("Window"));


                TableForGeneralResuts.ListRowNames = new List<string>();
                TableForGeneralResuts.ListTags = new List<object>();

                cDesignerSplitter MainSplitter = new cDesignerSplitter();
                //cDesignerColumn MainSplitter = new cDesignerColumn();

                int IdxNode = 0;
                foreach (cListWells TmpListWells in this.Input)
                {
                    // List<cDescriptorType> LType = new List<cDescriptorType>();
                    //  LType.Add(ListSelectedDesc[i]);
                    cExtendedTable CompleteTable = TmpListWells.GetAverageDescriptorValues(ListSelectedDesc, true);

                    //cExtendedTable CompleteTable = GLP.GetOutPut();

                    cCurveForGraph CFG = new cCurveForGraph();
                    CFG.SetInputData(CompleteTable);
                    CFG.Run();

                    cSigmoidFitting SF = new cSigmoidFitting();
                    SF.SetInputData(CompleteTable);
                    if (SF.Run().IsSucceed == false) continue;

                    // double Ratio = LR.GetOutPut()[0][LR.GetOutPut().Count - 1] / SF.GetOutPut()[0][SF.GetOutPut().Count - 1];

                    cANOVA A = new cANOVA();
                    cExtendedTable NewTable = CFG.ListPtValues.Crop(0, CFG.ListPtValues.Count - 1, 1, CFG.ListPtValues[0].Count - 1);
                    A.SignificanceThreshold = 1E-11;
                    A.SetInputData(NewTable);
                    A.Run();

                    cExtendedTable Sigmoid = SF.GetFittedRawValues(CFG.GetListXValues());
                    CompleteTable[0] = Sigmoid[1];
                    CompleteTable[0].Name = ListSelectedDesc[0].GetName() + "\n" + Sigmoid[1].Name;
                    cDesignerSplitter DS = new cDesignerSplitter();

                    //cViewerTableAsRichText VT = new cViewerTableAsRichText();
                    cViewerTable VT = new cViewerTable();
                    cExtendedTable TableResults = SF.GetOutPut();

                    if ((A.GetOutPut() != null) && (A.GetOutPut().Count > 0))
                    {
                        TableResults[0].Add(A.GetOutPut()[0][0]);
                        TableResults[0].Add(A.GetOutPut()[0][1]);
                        TableResults.ListRowNames.Add("p-Value");
                        TableResults.ListRowNames.Add("Rejected?");

                        TableForGeneralResuts[0].Add(A.GetOutPut()[0][0]);
                    }
                    else
                    {
                        TableForGeneralResuts[0].Add(1);
                    }

                    TableResults.Name = TV.Nodes[IdxNode].Text;
                    TableResults[0].Name = "Fitting Parameters";
                    VT.SetInputData(TableResults);
                    VT.DigitNumber = -1;
                    VT.Run();

                    cViewerGraph1D VS1 = new cViewerGraph1D();
                  
                    cExtendedTable MyTable = new cExtendedTable(Sigmoid[1]);
                    MyTable.Name = TV.Nodes[IdxNode].Text;
                    VS1.SetInputData(MyTable);
                    VS1.AddCurve(CFG);

                    VS1.Chart.X_AxisValues = Sigmoid[0];
                    VS1.Chart.IsLogAxis = true;
                    VS1.Chart.IsLine = true;
                    VS1.Chart.IsShadow = false;
                    VS1.Chart.Opacity = 210;
                    VS1.Chart.LineWidth = 3;
                    VS1.Chart.MarkerSize = 8;
                    //VS1.Chart.IsDisplayValues = true;
                    VS1.Chart.LabelAxisX = "Concentration";
                    VS1.Chart.LabelAxisY = CompleteTable[1].Name;
                    VS1.Chart.XAxisFormatDigitNumber = -1;
                    VS1.Chart.IsZoomableX = true;

                    Classes.Base_Classes.General.cLineVerticalForGraph VLForEC50 = new Classes.Base_Classes.General.cLineVerticalForGraph(SF.GetOutPut()[0][2]);
                    //VLForEC50.AddText("EC50: " + SF.GetOutPut()[0][2].ToString("e3")/* + "\nError Ratio:" + Ratio.ToString("N4")*/);
                    VS1.Chart.ListVerticalLines.Add(VLForEC50);

                    TableForGeneralResuts.ListRowNames.Add(TV.Nodes[IdxNode].Text);
                    TableForGeneralResuts.ListTags.Add((Chart)VS1.Chart);//ListSelectedDesc[0]);

                    //EC50
                    TableForGeneralResuts[1].Add(SF.GetOutPut()[0][2]);

                    // Slope
                    TableForGeneralResuts[2].Add(SF.GetOutPut()[0][3]);

                    // Bottom
                    TableForGeneralResuts[3].Add(SF.GetOutPut()[0][0]);

                    // Top
                    TableForGeneralResuts[4].Add(SF.GetOutPut()[0][1]);

                    // Window
                    double Window = SF.GetOutPut()[0][1] / SF.GetOutPut()[0][0];
                    TableForGeneralResuts[5].Add(Window);

                    VS1.Chart.ArraySeriesInfo = new cSerieInfoDesign[CompleteTable.Count];

                    for (int IdxCurve = 0; IdxCurve < CompleteTable.Count; IdxCurve++)
                    {
                        cSerieInfoDesign TmpSerieInfo = new cSerieInfoDesign();
                        TmpSerieInfo.color = GlobalInfo.ListCellularPhenotypes[IdxCurve % GlobalInfo.ListCellularPhenotypes.Count].ColourForDisplay;
                        TmpSerieInfo.markerStyle = MarkerStyle.None;

                        VS1.Chart.ArraySeriesInfo[IdxCurve] = TmpSerieInfo;
                    }

                    VS1.Run();

                    DS.SetInputData(VS1.GetOutPut());
                    DS.SetInputData(VT.GetOutPut());
                    DS.Orientation = Orientation.Horizontal;
                    DS.Title = TV.Nodes[IdxNode++].Text; //TmpListWells.ti;// ListSelectedDesc[0].GetName();
                    DS.Run();
                    DT.SetInputData(DS.GetOutPut());
                }

                DT.Run();
                cExtendedControl TextEC = DT.GetOutPut();
                if (TextEC == null) return;

                TextEC.Width = 0;
                TextEC.Height = 0;

                TextEC.Anchor = (System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom
                        | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right);

                MainSplitter.SetInputData(TextEC);

                cSort S = new cSort();
                S.SetInputData(TableForGeneralResuts);
                S.IsAscending = true;
                S.Run();

                cViewerTable VTForEC50 = new cViewerTable();
                cExtendedTable RT = S.GetOutPut();
                RT.Name = cWell.Parent.ListDescriptors.GetActiveDescriptor().GetName();
                VTForEC50.SetInputData(RT);
                VTForEC50.DigitNumber = -1;
                VTForEC50.Run();

                MainSplitter.SetInputData(VTForEC50.GetOutPut());

                MainSplitter.Orientation = Orientation.Vertical;
                MainSplitter.Run();

                cDisplayToWindow DTW = new cDisplayToWindow();
                DTW.SetInputData(MainSplitter.GetOutPut());
                DTW.Title = "DRC analysis [" + cWell.Parent.ListDescriptors.GetActiveDescriptor().GetName() + "]";

                DTW.Run();
                DTW.Display();
            }

        }

        void ToolStripMenuItem_ExpandAll_Click(object sender, EventArgs e)
        {
            TV.ExpandAll();
        }

        void ToolStripMenuItem_CollapseAll_Click(object sender, EventArgs e)
        {
            TV.CollapseAll();
        }
    }
}
